﻿Imports SLFileManager.FileManagerService
Imports System.Collections.ObjectModel

Partial Public Class MainPage
    Inherits UserControl

    Private treeObj As ObservableCollection(Of ServerFolder)

    Private Shared _DomainPathName As String
    Private Shared Property DomainPathName() As String
        Get
            If _DomainPathName = Nothing And Windows.Browser.HtmlPage.Document.QueryString.ContainsKey("domain") Then
                _DomainPathName = Windows.Browser.HtmlPage.Document.QueryString("domain")
            End If
            If String.IsNullOrEmpty(_DomainPathName) Then
                _DomainPathName = String.Empty
            End If
            Return _DomainPathName
        End Get
        Set(ByVal value As String)
            _DomainPathName = value
        End Set
    End Property
    Private Shared _TypePathName As String
    Private Shared Property TypePathName() As String
        Get
            If _TypePathName = Nothing And Windows.Browser.HtmlPage.Document.QueryString.ContainsKey("type") Then
                _TypePathName = Windows.Browser.HtmlPage.Document.QueryString("type")
            End If
            If String.IsNullOrEmpty(_TypePathName) Then
                _TypePathName = String.Empty
            End If
            Return _TypePathName
        End Get
        Set(ByVal value As String)
            _TypePathName = value
        End Set
    End Property
    Private Shared _SubTypePathName As String
    Private Shared Property SubTypePathName() As String
        Get
            If _SubTypePathName = Nothing And Windows.Browser.HtmlPage.Document.QueryString.ContainsKey("subtype") Then
                _SubTypePathName = Windows.Browser.HtmlPage.Document.QueryString("subtype")
            End If
            If String.IsNullOrEmpty(_SubTypePathName) Then
                _SubTypePathName = String.Empty
            End If
            Return _SubTypePathName
        End Get
        Set(ByVal value As String)
            _SubTypePathName = value
        End Set
    End Property
    Private Shared _OpenModal As Boolean = False
    Private Shared Property OpenModal() As Boolean
        Get
            If Windows.Browser.HtmlPage.Document.QueryString.ContainsKey("OpenModal") Then
                Dim omstr = Windows.Browser.HtmlPage.Document.QueryString("OpenModal")
                If omstr.ToUpper = "T" Then
                    _OpenModal = True
                End If
            End If
            Return _OpenModal
        End Get
        Set(ByVal value As Boolean)
            _OpenModal = value
        End Set
    End Property
    Private Shared Property CurrentFolderName() As String
        Get
            Return _currentFolder._FolderName
        End Get
        Set(ByVal value As String)
            _currentFolder._FolderName = value
        End Set
    End Property
    Private Shared ReadOnly Property CurrentFolderPath() As String
        Get
            Return _currentFolder._FullPath
        End Get
    End Property
    Private Shared ReadOnly Property CurrentFolderURL() As String
        Get
            Return _currentFolder._URLPath
        End Get
    End Property
    Private Shared _currentFolder As ServerFolder
    Private Shared Property currentFolder() As ServerFolder
        Get
            Return _currentFolder
        End Get
        Set(ByVal value As ServerFolder)
            _currentFolder = value
        End Set
    End Property
    Private BackFromAsyncLoad As Boolean = False

    Public Sub New()
        InitializeComponent()

        FillFolderTree()
    End Sub
    Private Sub FillFolderTree()
        Dim serviceClient As FileManagerServiceClient = GetServiceClient()
        If Not String.IsNullOrEmpty(DomainPathName) And Not String.IsNullOrEmpty(TypePathName) And Not String.IsNullOrEmpty(SubTypePathName) Then
            AddHandler serviceClient.GetFileTreeDomainAndTypeAndSubTypeCompleted, AddressOf GetFileTreeDomainAndTypeAndSubTypeCompleted
            serviceClient.GetFileTreeDomainAndTypeAndSubTypeAsync(DomainPathName, TypePathName, SubTypePathName)
        ElseIf Not String.IsNullOrEmpty(DomainPathName) And Not String.IsNullOrEmpty(TypePathName) Then
            AddHandler serviceClient.GetFileTreeDomainAndTypeCompleted, AddressOf GetFileTreeDomainAndTypeCompleted
            serviceClient.GetFileTreeDomainAndTypeAsync(DomainPathName, TypePathName)
        ElseIf Not String.IsNullOrEmpty(DomainPathName) Then
            AddHandler serviceClient.GetFileTreeDomainCompleted, AddressOf GetFileTreeDomainCompleted
            serviceClient.GetFileTreeDomainAsync(DomainPathName)
        Else
            AddHandler serviceClient.GetFileTreeAllCompleted, AddressOf GetFileTreeAllCompleted
            serviceClient.GetFileTreeAllAsync()
        End If
        ' Sluit de client altijd af.
        serviceClient.CloseAsync()
    End Sub

    Private Sub GetFileTreeDomainAndTypeAndSubTypeCompleted(ByVal sender As Object, ByVal e As GetFileTreeDomainAndTypeAndSubTypeCompletedEventArgs)
        treeObj = e.Result
        TVFolders.ItemsSource = treeObj
        BackFromAsyncLoad = True
        If currentFolder Is Nothing Then
            currentFolder = treeObj(0)
        End If
        'DGfiles.ItemsSource = treeObj(0)._Files
        'SetPathItems(treeObj(0))
    End Sub
    Private Sub GetFileTreeDomainAndTypeCompleted(ByVal sender As Object, ByVal e As GetFileTreeDomainAndTypeCompletedEventArgs)
        treeObj = e.Result
        TVFolders.ItemsSource = treeObj
        BackFromAsyncLoad = True
        If currentFolder Is Nothing Then
            currentFolder = treeObj(0)
        End If
        'DGfiles.ItemsSource = treeObj(0)._Files
        'SetPathItems(treeObj(0))
    End Sub
    Private Sub GetFileTreeDomainCompleted(ByVal sender As Object, ByVal e As GetFileTreeDomainCompletedEventArgs)
        treeObj = e.Result
        TVFolders.ItemsSource = treeObj
        BackFromAsyncLoad = True
        If currentFolder Is Nothing Then
            currentFolder = treeObj(0)
        End If
        'DGfiles.ItemsSource = treeObj(0)._Files
        'SetPathItems(treeObj(0))
    End Sub
    Private Sub GetFileTreeAllCompleted(ByVal sender As Object, ByVal e As GetFileTreeAllCompletedEventArgs)
        treeObj = e.Result
        TVFolders.ItemsSource = treeObj(0)._SubFolders
        BackFromAsyncLoad = True
        If currentFolder Is Nothing Then
            currentFolder = treeObj(0)._SubFolders(0)
        End If
        'DGfiles.ItemsSource = treeObj(0)._SubFolders(0)._Files
        'SetPathItems(treeObj(0)._SubFolders(0))
    End Sub

    Private Sub TVFolders_LayoutUpdated(ByVal sender As Object, ByVal e As System.EventArgs) Handles TVFolders.LayoutUpdated
        If BackFromAsyncLoad Then
            SelectFolder(CurrentFolderPath, CurrentFolderName)
            BackFromAsyncLoad = False
        End If
    End Sub
    Public Sub SelectFolder(ByVal serverPath As String, ByVal serverName As String)
        'For Each treeItem As ServerFolder In TVFolders.Items
        Dim item As TreeViewItem = TVFolders.FindContainer( _
            Function(t) DirectCast(t.DataContext, ServerFolder)._FullPath = serverPath _
                And DirectCast(t.DataContext, ServerFolder)._FolderName = serverName)
        If item IsNot Nothing Then
            item.IsSelected = True
        End If
        'Next
    End Sub
    Private Sub TVFolders_SelectedItemChanged(ByVal sender As Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of Object)) Handles TVFolders.SelectedItemChanged
        Dim fld As ServerFolder = e.NewValue
        If fld Is Nothing Then
            'Dim a = e.OriginalSource
        Else
            currentFolder = fld
            DGfiles.ItemsSource = fld._Files
            SetPath()
            SetUploadPath()
        End If
    End Sub
    Private Sub SetPath()
        If CurrentFolderPath.Length > 50 Then
            Path.Text = "..." & Right(CurrentFolderPath & "\" & CurrentFolderName, 50)
            PathTooltip.Text = CurrentFolderPath & "\" & CurrentFolderName
        Else
            Path.Text = CurrentFolderPath & "\" & CurrentFolderName
            PathTooltip.Text = CurrentFolderPath & "\" & CurrentFolderName
        End If
    End Sub
    Sub SetUploadPath()
        Dim src As String = Application.Current.Host.Source.ToString()
        Dim applicationRoot As String = src.Substring(0, src.IndexOf("ClientBin"))
        ''Where CLientBin is the location of your XAP file
        FileUploadCtrl.UploadUrl = New Uri(Windows.Browser.HtmlPage.Document.DocumentUri, "FileUpload.ashx?path=" & CurrentFolderURL & "/" & CurrentFolderName)
    End Sub

    Private Sub TVDragDrop_Drop(ByVal sender As Object, ByVal e As Microsoft.Windows.DragEventArgs) Handles TVDragDrop.Drop
        If e.OriginalSource.GetType Is GetType(TextBlock) Then
            Dim thisServerFolder As ServerFolder = DirectCast(e.OriginalSource, TextBlock).DataContext
            Dim args As ItemDragEventArgs = e.Data.GetData(e.Data.GetFormats()(0))
            Dim data = args.Data
            For Each thisitem In data
                If thisitem.item.GetType Is GetType(ServerFile) Then
                    Dim ThisServerFile As ServerFile = thisitem.item
                    If ThisServerFile._FullPath <> thisServerFolder._FullPath & "\" & thisServerFolder._FolderName Then
                        Dim serviceClient As FileManagerServiceClient = GetServiceClient()
                        AddHandler serviceClient.UpdateFileCompleted, AddressOf UpdateFileCompleted
                        serviceClient.UpdateFileAsync(ThisServerFile._FullPath, ThisServerFile._OrigFileName, thisServerFolder._FullPath & "\" & thisServerFolder._FolderName, ThisServerFile._FileName)
                        ' Sluit de client altijd af.
                        serviceClient.CloseAsync()
                    End If
                Else
                    Dim itemServerFolder As ServerFolder = thisitem.item
                    If itemServerFolder._FullPath <> thisServerFolder._FullPath & "\" & thisServerFolder._FolderName Then
                        Dim serviceClient As FileManagerServiceClient = GetServiceClient()
                        AddHandler serviceClient.UpdateFolderCompleted, AddressOf UpdateFolderCompleted
                        serviceClient.UpdateFolderAsync(itemServerFolder._FullPath, itemServerFolder._FolderName, thisServerFolder._FullPath & "\" & thisServerFolder._FolderName, itemServerFolder._FolderName)
                        ' Sluit de client altijd af.
                        serviceClient.CloseAsync()
                    End If
                End If
            Next
        End If
    End Sub
    Sub BtnRefresh_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Reset()
    End Sub
    Private Sub Reset()
        Dim serviceClient As FileManagerServiceClient = GetServiceClient()
        AddHandler serviceClient.ResetCompleted, AddressOf ResetCompleted
        serviceClient.ResetAsync()
        ' Sluit de client altijd af.
        serviceClient.CloseAsync()
    End Sub
    Sub BtnUpload_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If PopupUpload.IsOpen = True Then
            PopupUpload.IsOpen = False
        Else
            PopupUpload.IsOpen = True
        End If
    End Sub
    Private Sub FileUploadCtrl_UploadCompleted(ByVal sender As Object, ByVal e As System.EventArgs) Handles FileUploadCtrl.UploadCompleted
        Reset()
    End Sub
    Private Sub ResetCompleted(ByVal sender As Object, ByVal e As ResetCompletedEventArgs)
        treeObj = Nothing
        FillFolderTree()
    End Sub

    Sub BtnCloseUpload_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        PopupUpload.IsOpen = False
    End Sub
    Sub BtnDeleteFolder_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim OKCancel = MessageBox.Show("Weet je zeker dat je het map wilt verwijderen?", "Verwijderen?", MessageBoxButton.OKCancel)
        If OKCancel = MessageBoxResult.OK Then
            Dim serviceClient As FileManagerServiceClient = GetServiceClient()
            AddHandler serviceClient.DeleteFolderCompleted, AddressOf DeleteFolderCompleted
            serviceClient.DeleteFolderAsync(CurrentFolderPath, CurrentFolderName)
            ' Sluit de client altijd af.
            serviceClient.CloseAsync()
        End If
    End Sub
    Private Sub DeleteFolderCompleted(ByVal sender As Object, ByVal e As DeleteFolderCompletedEventArgs)
        If e.Error Is Nothing Then
            Status.Text = e.Result
        Else
            Status.Text = "error on add in service"
        End If
        treeObj = Nothing
        FillFolderTree()
    End Sub
    Sub BtnRenameFolder_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If PopupFolderName.IsOpen = True Then
            PopupFolderName.IsOpen = False
            TbFolderName.Text = ""
        Else
            PopupFolderName.IsOpen = True
            TbFolderName.Text = CurrentFolderName
            PopupAddFolder.IsOpen = False
        End If
    End Sub
    Sub BtnFolderNameOK_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If Not String.IsNullOrEmpty(TbFolderName.Text.Trim) AndAlso TbFolderName.Text.Trim <> CurrentFolderName Then
            Dim serviceClient As FileManagerServiceClient = GetServiceClient()
            AddHandler serviceClient.UpdateFolderCompleted, AddressOf UpdateFolderCompleted
            serviceClient.UpdateFolderAsync(CurrentFolderPath, CurrentFolderName, CurrentFolderPath, TbFolderName.Text)
            ' Sluit de client altijd af.
            serviceClient.CloseAsync()
            CurrentFolderName = TbFolderName.Text
            'Dim entity As ServerFile = TVFolders.SelectedItem
        End If
    End Sub
    Private Sub UpdateFolderCompleted(ByVal sender As Object, ByVal e As UpdateFolderCompletedEventArgs)
        If e.Error Is Nothing Then
            Status.Text = e.Result
        Else
            Status.Text = "error on add in service"
        End If
        treeObj = Nothing
        FillFolderTree()
        TbFolderName.Text = String.Empty
        PopupFolderName.IsOpen = False
    End Sub
    Sub BtnAddFolder_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If PopupAddFolder.IsOpen = True Then
            PopupAddFolder.IsOpen = False
            TbAddFolder.Text = ""
        Else
            PopupAddFolder.IsOpen = True
            TbAddFolder.Text = ""
            PopupFolderName.IsOpen = False
        End If
    End Sub
    Sub BtnAddFolderOK_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If Not String.IsNullOrEmpty(TbAddFolder.Text.Trim) AndAlso TbAddFolder.Text.Trim <> CurrentFolderName Then
            Dim serviceClient As FileManagerServiceClient = GetServiceClient()
            AddHandler serviceClient.AddFolderCompleted, AddressOf AddFolderCompleted
            serviceClient.AddFolderAsync(CurrentFolderPath & "\" & CurrentFolderName, TbAddFolder.Text)
            ' Sluit de client altijd af.
            serviceClient.CloseAsync()
        End If
    End Sub
    Private Sub AddFolderCompleted(ByVal sender As Object, ByVal e As AddFolderCompletedEventArgs)
        If e.Error Is Nothing Then
            Status.Text = e.Result
        Else
            Status.Text = "error on add in service"
        End If
        treeObj = Nothing
        FillFolderTree()
        TbAddFolder.Text = String.Empty
        PopupAddFolder.IsOpen = False
    End Sub

    'Sub btnEdit_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    '    Dim entity As ServerFile = DirectCast(sender, Button).DataContext
    '    DGfiles.SelectedItem = entity
    '    MessageBox.Show("Selected row: " & DGfiles.SelectedIndex & " - " & entity._FileName & ", " & entity._FileID)
    'End Sub
    'Sub btnCancel_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    '    Dim entity As ServerFile = DirectCast(sender, Button).DataContext
    '    DGfiles.SelectedItem = entity
    '    MessageBox.Show("Selected row: " & DGfiles.SelectedIndex & " - " & entity._FileName & ", " & entity._FileID)
    'End Sub
    Sub btnSelect_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim entity As ServerFile = DirectCast(sender, Button).DataContext
        If Windows.Browser.HtmlPage.Document.QueryString.ContainsKey("CKEditorFuncNum") Then
            Windows.Browser.HtmlPage.Window.Eval("window.opener.CKEDITOR.tools.callFunction(" & _
                                                 Windows.Browser.HtmlPage.Document.QueryString("CKEditorFuncNum") & _
                                                 ", '" & entity._URLPath & entity._FileName & "', '');")
        Else
            '"window.returnValue = '" & entity._URLPath & "'; window.close();"
            Windows.Browser.HtmlPage.Window.SetProperty("returnValue", "/" & entity._URLPath & entity._FileName)
        End If
        Windows.Browser.HtmlPage.Window.Invoke("close")
    End Sub
    Private Sub DGfiles_CellEditEnding(ByVal sender As Object, ByVal e As DataGridCellEditEndingEventArgs) Handles DGfiles.CellEditEnding
        If e.EditAction = DataGridEditAction.Commit Then
            Dim entity As ServerFile = e.Row.DataContext
            Dim NewFileName As String
            If e.EditingElement.GetType Is GetType(TextBox) Then
                NewFileName = DirectCast(e.EditingElement, TextBox).Text
                'MessageBox.Show("" & entity._FileName & ", " & entity._FileID)
                If entity._OrigFileName <> NewFileName Then
                    Dim serviceClient As FileManagerServiceClient = GetServiceClient()
                    AddHandler serviceClient.UpdateFileCompleted, AddressOf UpdateFileCompleted
                    serviceClient.UpdateFileAsync(entity._FullPath, entity._OrigFileName, entity._FullPath, NewFileName)
                    ' Sluit de client altijd af.
                    serviceClient.CloseAsync()
                End If
            End If
        Else
        End If
    End Sub
    Private Sub UpdateFileCompleted(ByVal sender As Object, ByVal e As UpdateFileCompletedEventArgs)
        If e.Error Is Nothing Then
            Status.Text = e.Result
        Else
            Status.Text = "error on update in service"
        End If
        treeObj = Nothing
        FillFolderTree()
    End Sub
    Sub btnDelete_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim entity As ServerFile = DirectCast(sender, Button).DataContext
        Dim OKCancel = MessageBox.Show("Weet je zeker dat je het bestand wilt verwijderen?", "Verwijderen?", MessageBoxButton.OKCancel)
        If OKCancel = MessageBoxResult.OK Then
            Dim serviceClient As FileManagerServiceClient = GetServiceClient()
            AddHandler serviceClient.DeleteFileCompleted, AddressOf DeleteFileCompleted
            serviceClient.DeleteFileAsync(entity._FullPath, entity._OrigFileName)
            ' Sluit de client altijd af.
            serviceClient.CloseAsync()
        End If
    End Sub
    Private Sub DeleteFileCompleted(ByVal sender As Object, ByVal e As DeleteFileCompletedEventArgs)
        If e.Error Is Nothing Then
            Status.Text = e.Result
        Else
            Status.Text = "error on delete in service"
        End If
        treeObj = Nothing
        FillFolderTree()
    End Sub
    Private Sub img_ImageFailed(ByVal sender As Object, ByVal e As ExceptionRoutedEventArgs)

    End Sub
    Private Sub btnSelect_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim link As Button = sender
        If OpenModal Then
            link.Visibility = Visibility.Visible
        Else
            link.Visibility = Visibility.Collapsed
        End If
    End Sub

    Private Function GetServiceClient() As FileManagerServiceClient
        Dim binding As New ServiceModel.BasicHttpBinding(
            If(Application.Current.Host.Source.Scheme.Equals("https",StringComparison.InvariantCultureIgnoreCase),
               ServiceModel.BasicHttpSecurityMode.Transport, ServiceModel.BasicHttpSecurityMode.None))
        binding.MaxReceivedMessageSize = Integer.MaxValue
        binding.MaxBufferSize = Integer.MaxValue
        'Dim address As ServiceModel.EndpointAddress = _
        '    New EndpointAddress(New Uri(Application.Current.Host.Source, "../FileManagerService.svc"))

        Dim thisUri As Uri = New Uri(Windows.Browser.HtmlPage.Document.DocumentUri, "FileManagerService.svc")
        Dim address As ServiceModel.EndpointAddress = New ServiceModel.EndpointAddress(thisUri)
        Dim serviceClient = New FileManagerServiceClient(binding, address)
        serviceClient.ClientCredentials.UserName.UserName = ""
        serviceClient.ClientCredentials.UserName.Password = ""
        Return serviceClient
    End Function

    Private Sub ExpandAll(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim i As Integer = 0
        While i < TVFolders.Items.Count
            ExpandAllTreeViewItems(DirectCast(TVFolders.ItemContainerGenerator.ContainerFromIndex(i), TreeViewItem))
            i = i + 1
        End While
    End Sub
    Private Sub ExpandAllTreeViewItems(ByVal currentTreeViewItem As TreeViewItem)
        If Not currentTreeViewItem.IsExpanded Then
            currentTreeViewItem.IsExpanded = True
            Dim GetOnRightThread As New ExpandAllTheTreeViewItems(AddressOf ExpandAllTreeViewItems)
            currentTreeViewItem.Dispatcher.BeginInvoke(GetOnRightThread, currentTreeViewItem)
        Else
            Dim i As Integer = 0
            While i < currentTreeViewItem.Items.Count
                Dim child As TreeViewItem = DirectCast(currentTreeViewItem.ItemContainerGenerator.ContainerFromIndex(i), TreeViewItem)
                ExpandAllTreeViewItems(child)
                i = i + 1
            End While
        End If
    End Sub
    Delegate Sub ExpandAllTheTreeViewItems(ByVal currentTreeViewItem As TreeViewItem)

    Private Sub CollapseAll(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim i As Integer = 0
        While i < TVFolders.Items.Count
            CollapseAllTreeViewItems(DirectCast(TVFolders.ItemContainerGenerator.ContainerFromIndex(i), TreeViewItem))
            i = i + 1
        End While
    End Sub
    Private Sub CollapseAllTreeViewItems(ByVal rootTreeViewItem As TreeViewItem)
        Dim treeViewItemsStack As New Stack(Of TreeViewItem)()
        treeViewItemsStack.Push(rootTreeViewItem)
        While treeViewItemsStack.Count <> 0
            Dim current As TreeViewItem = treeViewItemsStack.Pop()
            current.IsExpanded = False

            Dim i As Integer = 0
            While i < current.Items.Count
                Dim tvi = TryCast(current.ItemContainerGenerator.ContainerFromIndex(i), TreeViewItem)
                If tvi IsNot Nothing Then
                    treeViewItemsStack.Push(tvi)
                End If
                i = i + 1
            End While
        End While
    End Sub
    Private Sub CollapseTopLevel(ByVal sender As Object, ByVal e As RoutedEventArgs)
        ' This iterates through the three top-level items only.
        For Each item In TVFolders.Items
            Dim tvi As TreeViewItem = TryCast(TVFolders.ItemContainerGenerator.ContainerFromItem(item), TreeViewItem)
            tvi.IsExpanded = False
        Next
    End Sub

End Class